<template>
  <div class="home-container">
    <!-- 轮播图区域 -->
    <div class="banner-container">
      <div
        class="banner-wrapper"
        :style="{
          transform: `translateY(-${currentIndex * 100}%)`,
          transition: isTransitioning ? 'transform 0.5s ease-in-out' : 'none',
        }"
      >
        <div
          class="banner-item"
          v-for="(item, index) in processedBannerList"
          :key="index"
        >
          <img :src="item.image" :alt="item.title" class="banner-image" />
          <div class="banner-content">
            <h3 class="banner-title">{{ item.title }}</h3>
            <p class="banner-description">{{ item.description }}</p>
          </div>
        </div>
      </div>

      <!-- 上下切换按钮 -->
      <div class="up-btn" @click="upBanner" v-if="bannerList.length > 1">
        <xyIcon type="up" :size="20"></xyIcon>
      </div>
      <div class="down-btn" @click="downBanner" v-if="bannerList.length > 1">
        <xyIcon type="down" :size="20"></xyIcon>
      </div>

      <!-- 指示器 -->
      <ul class="banner-indicator" v-if="bannerList.length > 1">
        <li
          class="indicator-item"
          :class="{ 'indicator-active': realIndex == index }"
          @click="setActive(index)"
          v-for="(item, index) in bannerList"
          :key="item.id"
        ></li>
      </ul>
    </div>
  </div>
</template>

<script>
import { getBannerList } from '@/api/home'
import xyIcon from '@/components/xyIcon.vue'

export default {
  name: 'HomeView',
  components: {
    xyIcon,
  },
  data() {
    return {
      bannerList: [],
      currentIndex: 1, // 从第一个真实图片开始
      timer: null,
      wheelTimer: null,
      isTransitioning: true,
    }
  },
  computed: {
    // 处理后的轮播图数据，用于无缝滚动
    processedBannerList() {
      if (this.bannerList.length === 0) return []
      // 在数组前后各添加一个图片，实现无缝滚动
      const lastItem = this.bannerList[this.bannerList.length - 1]
      const firstItem = this.bannerList[0]
      return [lastItem, ...this.bannerList, firstItem]
    },
    // 真实索引，用于指示器显示
    realIndex() {
      if (this.bannerList.length === 0) return 0
      if (this.currentIndex === 0) return this.bannerList.length - 1
      if (this.currentIndex === this.processedBannerList.length - 1) return 0
      return this.currentIndex - 1
    },
  },
  methods: {
    upBanner() {
      if (this.bannerList.length === 0) return
      this.currentIndex--
      this.checkBoundary()
    },
    downBanner() {
      if (this.bannerList.length === 0) return
      this.currentIndex++
      this.checkBoundary()
    },
    handleWheel(event) {
      // 防止页面滚动
      event.preventDefault()

      // 检测滚轮方向
      const delta = Math.sign(event.deltaY)

      // 添加防抖，避免快速滚动时频繁切换
      if (this.wheelTimer) {
        clearTimeout(this.wheelTimer)
      }

      this.wheelTimer = setTimeout(() => {
        if (delta > 0) {
          // 向下滚动，切换到下一张
          this.downBanner()
        } else {
          // 向上滚动，切换到上一张
          this.upBanner()
        }
        // 滚轮切换后重新计时自动轮播
        this.resetAutoPlay()
      }, 100)
    },
    setActive(i) {
      if (this.bannerList.length === 0) return
      this.currentIndex = i + 1 // 因为前面添加了一个元素
      this.resetAutoPlay()
    },
    checkBoundary() {
      // 检查边界，实现无缝滚动
      if (this.currentIndex === 0) {
        // 滚动到最前面时，快速跳转到倒数第二张（真实最后一张）
        setTimeout(() => {
          this.isTransitioning = false
          this.currentIndex = this.processedBannerList.length - 2
          setTimeout(() => {
            this.isTransitioning = true
          }, 50)
        }, 500)
      } else if (this.currentIndex === this.processedBannerList.length - 1) {
        // 滚动到最后面时，快速跳转到第二张（真实第一张）
        setTimeout(() => {
          this.isTransitioning = false
          this.currentIndex = 1
          setTimeout(() => {
            this.isTransitioning = true
          }, 50)
        }, 500)
      }
    },
    startAutoPlay() {
      if (this.bannerList.length <= 1) return
      this.timer = setInterval(() => {
        this.downBanner()
      }, 3000)
    },
    stopAutoPlay() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },
    resetAutoPlay() {
      this.stopAutoPlay()
      this.startAutoPlay()
    },
  },
  async mounted() {
    try {
      const response = await getBannerList()
      this.bannerList = response || []
      this.startAutoPlay()

      // 添加滚轮事件监听
      this.$el.addEventListener('wheel', this.handleWheel, { passive: false })
    } catch (error) {
      console.error('获取轮播图数据失败:', error)
      this.bannerList = []
    }
  },
  beforeDestroy() {
    this.stopAutoPlay()
    // 清理滚轮事件监听
    if (this.$el) {
      this.$el.removeEventListener('wheel', this.handleWheel)
    }
    // 清理滚轮防抖定时器
    if (this.wheelTimer) {
      clearTimeout(this.wheelTimer)
    }
  },
}
</script>

<style scoped>
.home-container {
  width: 100%;
  height: 100vh;
  position: relative;
  overflow: hidden;
}

.banner-container {
  width: 100%;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.banner-wrapper {
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease-in-out;
}

.banner-item {
  width: 100%;
  height: 100%;
  position: relative;
}

.banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.banner-content {
  position: absolute;
  bottom: 100px;
  left: 50px;
  color: white;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  max-width: 500px;
}

.banner-title {
  font-size: 2.5rem;
  font-weight: bold;
  margin-bottom: 1rem;
}

.banner-description {
  font-size: 1.2rem;
  line-height: 1.6;
}

.up-btn,
.down-btn {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  width: 50px;
  height: 50px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  z-index: 10;
}

.up-btn:hover,
.down-btn:hover {
  background: rgba(255, 255, 255, 1);
  transform: translateX(-50%) scale(1.1);
}

.up-btn {
  top: 30px;
}

.down-btn {
  bottom: 30px;
}

.banner-indicator {
  position: absolute;
  right: 30px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  gap: 10px;
  list-style: none;
  margin: 0;
  padding: 0;
  z-index: 10;
}

.indicator-item {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.5);
  cursor: pointer;
  transition: all 0.3s ease;
}

.indicator-item:hover {
  background: rgba(255, 255, 255, 0.8);
}

.indicator-active {
  background: rgba(255, 255, 255, 1);
  transform: scale(1.2);
}
</style>
